import {isArray} from './type'

// 上传图片
export function uploadImage(options) {
	const {
		url,
		name = 'data',
		loadingTtile = '上传中',
		count = 1,
		maxSize = 3,
		hideLoadingTime = 500,
		timeout = 80000,
		loading = true,
		header = {},
		formData = {},
		imageTypes = ['png', 'jpg', 'jpeg']
	} = options
	
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count,
			sizeType: ['compressed'],
			success(res) {
				const file = res.tempFiles[0]
				console.log('chooseImage success, temp path is', res.tempFiles[0])
				if (file.size > maxSize * 1024 *1024) {
					uni.showModal({
						showCancel: false,
						content: `图片不能超过${maxSize}MB`
					})
					return
				}
				
				const imageTypes = ['png', 'jpg', 'jpeg']
				const fs = uni.getFileSystemManager()
				
				fs.readFile({
					filePath: file.path,
					success(fsRes) {
						let fileData = res.data
						uni.getImageInfo({
							src: file.path,
							success(imgInfo) {
								if (!isArray(imageTypes)) {
									throw new Error(`options.imageTypes must be array, not of ${typeof imageTypes}`)
								}
								if (!imageTypes.includes(imgInfo.type)) {
									uni.showModal({
										title: '温馨提示！',
										showCancel: false,
										content: '请上传正确类型的图片'
									})
									return
								}
								uni.showLoading({title: loadingTtile})
								uni.uploadFile({
									url,
									name,
									header,
									timeout,
									formData,
									filePath: file.path,
									fileType: 'image',
									success(result) {
										uni.showToast({
											title: '上传成功',
											icon: 'success',
											duration: 1000
										})
										
										resolve({...result, ...res.tempFiles[0]})
									},
									fail(err) {
										uni.showModal({
											content: err.errMsg,
											showCancel: false
										})
										
										reject(err)
									},
									complete() {
										setTimeout(() => uni.hideLoading(), hideLoadingTime)
									}
								})
							}
						})
					}
				})
			},
			fail(err) {
				console.log('chooseImage fail', err)
				// #ifdef MP
				uni.getSetting({
					success(res) {
						let authStatus = res.authSetting['scope.album']
						if (!authStatus) {
							uni.showModal({
								title: '授权失败',
								content: '需要从您的相册获取图片，请在设置界面打开相关权限',
								success(confirm) {
									if (res.confirm) {
										uni.openSetting()
									}
								}
							})
						}
					}
				})
				// #endif
			}
		})
	})
}